﻿using System.Xml.Linq;

namespace Ornament.NHibernateHelper
{
    public class Mapping
    {
        private const string assembly = "assembly";
        private const string file = "file";
        private const string resource = "resource";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapping"></param>
        internal Mapping(XElement mapping)
        {
            Element = mapping;
            IsInFile = true;
        }

        internal bool IsInFile { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Assembly
        {
            get { return GetAttributeValue(assembly); }
            set { SetValue(assembly, value); }
        }

        /// <summary>
        /// 
        /// </summary>
        public string File
        {
            get { return GetAttributeValue(file); }
            set { SetValue(file, value); }
        }

        /// <summary>
        /// 
        /// </summary>
        public string Resource
        {
            get { return GetAttributeValue(resource); }
            set { SetValue(resource, value); }
        }

        internal XElement Element { set; get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetAttributeValue(string key)
        {
            XAttribute result = Element.Attribute(key);
            return result != null ? result.Value : null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private void SetValue(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
                return;
            if (value == null)
                return;
            XAttribute result = Element.Attribute(key);
            
            if (result == null)
                Element.Add(new XAttribute(key, value));
            else
                result.Value = value;
        }
    }
}